<script setup lang="tsx">
import { reactive, ref, unref, markRaw, shallowRef, provide, type Component } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import Add from './component/Add.vue'
import Modify from './component/Modify.vue'
import Details from './component/Details.vue'
import { ElCollapseTransition } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { useSearch } from '@/hooks/web/useSearch'
import { getListApi, delUserApi, type Row } from '@/api/system/staff'
import { searchProjectCateApi } from '@/api/utils/search'

defineOptions({
  name: 'Account'
})
const comId = reactive({
  Add: markRaw(Add),
  Modify: markRaw(Modify),
  Details: markRaw(Details)
})
const { searchRegister, searchMethods } = useSearch()
const { setSchema } = searchMethods
const searchUser = async (query) => {
  if (query && Object.values(query).every((item) => item !== '')) {
    setSchema([
      {
        field: Object.keys(query)[0],
        path: 'componentProps.loading',
        value: true
      }
    ])
    const params = {
      ...query,
      field: 'id,user_name,real_name,mobile'
    }
    const res = await searchProjectCateApi(params)
    if (res) {
      setSchema([
        {
          field: Object.keys(query)[0],
          path: 'componentProps.options',
          value: res.data.list.map((item) => {
            return {
              label: item[Object.keys(query)[0]],
              value: item[Object.keys(query)[0]]
            }
          })
        }
      ])
    }
    setSchema([
      {
        field: Object.keys(query)[0],
        path: 'componentProps.loading',
        value: false
      }
    ])
  }
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: 'selection' }
  },
  {
    field: 'id',
    label: '账号ID',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'user_name',
    label: '登录账号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'mobile',
    label: '手机号',
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'role_names',
    label: '角色',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'create_time',
    label: '创建时间',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true }
  },
  {
    field: 'action',
    width: '260px',
    label: '操作',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      slots: {
        default: ({ row }) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => action(comId['Modify'], row)}>
                编辑
              </BaseButton>
              <BaseButton type="primary" onClick={() => action(comId['Details'], row)}>
                详情
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const ids = ref<string[]>([])

const searchParams = ref()
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const tableData = ref([] as any)
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getListApi({
      page: unref(currentPage),
      limit: unref(pageSize),
      ...unref(searchParams)
    })
    tableData.value = res.data.list
    return {
      list: res.data.list,
      total: res.data.count
    }
  },
  fetchDelApi: async () => {
    const res = await delUserApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const showCollapse = ref(false)
let currentAction = shallowRef()
let currentRow = ref<Row | undefined>(undefined)
const action = (component: Component, row?: Row) => {
  currentAction.value = component
  currentRow.value = row
  if (showCollapse.value === false) showCollapse.value = true
}
const closeCollapse = () => {
  showCollapse.value = false
}
const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
provide('currentRow', currentRow)
</script>

<template>
  <ContentWrap>
    <Search
      @register="searchRegister"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <BaseButton type="primary" @click="action(comId['Add'])">新增</BaseButton>
      <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton>
    </div>

    <el-collapse-transition>
      <component
        :is="currentAction"
        @close="closeCollapse"
        @get-list="getList"
        v-show="showCollapse"
      />
    </el-collapse-transition>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
